package cn.biplam.setup.code;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import cn.biplam.back.jda.Jda;
import cn.biplam.back.sql.dml.Insert;
import cn.biplam.common.client.DataFilter;
import cn.biplam.common.client.DbResource;
import cn.biplam.common.tools.DEBUG;
import cn.biplam.common.tools.TOOLS;
import cn.biplam.common.wrapper.ErrorMessage;
import cn.biplam.common.wrapper.sqlresult.SqlResult;
import cn.biplam.setup.code.ExchangeCodeData.Code_Type;
import cn.biplam.setup.code.ajx.AjxCodeData;
import cn.biplam.setup.code.bean.BeanCodeData;
import cn.biplam.setup.code.opera.OperatorCodeData;
import cn.biplam.setup.code.page.PageCodeData;

public class ExchangeCodeAutoMatch {

	private ArrayList<String> fullPathList;
	private ArrayList<String> classNameList;
	
	/**
     * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
     *
     * @param packageName The base package
     * @return The classes
     * @throws ClassNotFoundException
     * @throws IOException
     */
    public void getClasses(String packageName) throws IOException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        assert classLoader != null;
        String path = packageName.replace('.', '/');
        Enumeration<URL> resources = classLoader.getResources(path);
        List<File> dirs = new ArrayList<File>();
        while (resources.hasMoreElements()) {
            URL resource = resources.nextElement();
            dirs.add(new File(resource.getFile().replace("%20", " ")));
        }
        fullPathList = new ArrayList<String>();
        classNameList = new ArrayList<String>();
        for (File directory : dirs) {
        	findClasses(directory, packageName);
        }
    }

    /**
     * Recursive method used to find all classes in a given directory and subdirs.
     *
     * @param directory   The base directory
     * @param packageName The package name for classes found inside the base directory
     * @return The classes
     * @throws ClassNotFoundException
     */
    private void findClasses(File directory, String packageName){
        if (!directory.exists()) {
            return;
        }
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                findClasses(file, packageName + "." + file.getName());
            } else if (file.getName().endsWith(".class")) {
            	classNameList.add(file.getName().substring(0, file.getName().length() - 6));
            	fullPathList.add(packageName + '.' + file.getName().substring(0, file.getName().length() - 6));
            }
        }
        return;
    }

	/**
	 * 获取所有类名列表
	 */
	public ArrayList<String> getClassNameList() {
		return classNameList;
	}
	
	/**
	 * 获取所有类完整路径列表
	 */
	public ArrayList<String> getFullPathList() {
		return fullPathList;
	}
    
	/**
	 * 将类信息写入数据库
	 */
	public void writeClassPathToDb(){
		try{
			String[] classSql = graWriteSql();
			if(classSql == null || classSql.length<1){
				return;
			}
			Jda mJda = new Jda(new DbResource(DbResource.RT));
			mJda.executeDMLBatch(classSql);
		}catch (Exception e) {
			DEBUG.println(e.getMessage());
		}
	}
	
	/**
	 * 更新所有匹配上的类路径
	 */
	public void updateAllCode(){
		ArrayList<String> sqls = new ArrayList<String>();
		try{
			compClassPath(sqls, Code_Type.Ajx_Code.toString(), new AjxCodeData());
			compClassPath(sqls, Code_Type.Operator_Code.toString(), new OperatorCodeData());
			compClassPath(sqls, Code_Type.Page_Code.toString(), new PageCodeData());
			compClassPath(sqls, Code_Type.Bean_Operator_Code.toString(), new BeanCodeData());
			if(sqls.size()>0){
				Jda mJda = new Jda(new DbResource(DbResource.RT));
				mJda.executeDMLBatch(TOOLS.listToStringArray(sqls));
			}
		}catch (Exception e) {
			DEBUG.println(e.getMessage());
		}
	}
	
	/**
	 * 获取所有原有代码的类名称及其路径
	 */
	private void compClassPath(ArrayList<String> sqls,String type,ExchangeCodeData codes) throws ErrorMessage{
		SqlResult ajxCodes = codes.getCodes();
		if(TOOLS.exist(ajxCodes)){
			String codePath = null;
			String codeClassName = null;
			String codeId = null;
			while(ajxCodes.next()){
				codePath = ajxCodes.getString(codes.CODE_ORG_CLASS_PATH);
				codeId = ajxCodes.getString(codes.CODE_ID);
				if(TOOLS.StringIsEmpty(codePath)){
					continue;
				}
				codeClassName = codePath.substring(codePath.lastIndexOf(".")+1,codePath.length());
				updateClassPath(codeClassName, codePath, codeId, codes, sqls);
			}
		}
	}
	
	/**
	 * 比较原有代码的类名和从文件扫描的类名,能在现有类中找到唯一类名与原有代码类名匹配则更新代码,否则打印出未匹配信息
	 */
	private void updateClassPath(String codeClassName,String codePath,String codeId,
			ExchangeCodeData codes,ArrayList<String> sqls) throws ErrorMessage{
		int firstIndex = this.classNameList.indexOf(codeClassName);
		int lastIndex = this.classNameList.lastIndexOf(codeClassName);
		if(firstIndex==-1){
			DEBUG.println("Can not find class "+codeClassName);
			return;
		}
		if(firstIndex == lastIndex){
			String classPath = this.fullPathList.get(firstIndex);
			DataFilter filter = new DataFilter();
			filter.put(codes.CODE_ID, codeId);
			filter.put(codes.CODE_CLASS_PATH, classPath);
			sqls.add(codes.getUpdateCodeSql(filter));
		}else{
			DEBUG.println("More than one class match to "+codeClassName +" !");
			DEBUG.println("such as "+ this.fullPathList.get(firstIndex)+ 
					" and "+ this.fullPathList.get(lastIndex));
		}
	}
	
	/**
	 * 获取写入类信息Sql
	 */
	private String[] graWriteSql(){
		assert !(this.classNameList==null);
		assert !(this.fullPathList==null);
		assert !(this.classNameList.size() == this.fullPathList.size());
		String tableName = "xrx_all_class";
		Insert insert = null;
		ArrayList<String> sqls = new ArrayList<String>();
		sqls.add(" delete from "+tableName);
		try{
			for(int i=0;i<classNameList.size();i++){
				insert = new Insert(tableName);
				insert.putStringField("class_name", classNameList.get(i));
				insert.putStringField("full_path", fullPathList.get(i));
				sqls.add(insert.getSimpleSql());
			}
		}catch (Exception e) {
			DEBUG.println(e.getMessage());
		}
		return TOOLS.listToStringArray(sqls);
	}
	
	public static void main(String[] args) throws ClassNotFoundException, IOException {
		ExchangeCodeAutoMatch rp = new ExchangeCodeAutoMatch();
		rp.getClasses("cn.biplam");
		rp.updateAllCode();
	}
}
